package com.tech.koufu.ui.view;

  
import java.util.ArrayList;
import java.util.List; 

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MainActivity;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;  
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.BuyStocksActivity;
import com.tech.koufu.ui.activity.login.LoginActivity;
import com.tech.koufu.ui.adapter.HomeBannersAdapter;  

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;

public class MainLoginFragment extends Fragment implements OnClickListener,OnPageChangeListener {
	private View view;
	private MyApplication myApp;
	private StringRequest stringRequest;
	private RequestQueue mRequestQueue;
	private ProgressBar pb_wait;
	private LinearLayout ly_mainlogin;
	/**
	 * 按钮 登录两种类别
	 */
	private ImageButton iv_nologin;
//	private Button btnLoginkf, btnLoginOther;
	/**
	 * 首页滚动图
	 */
	protected List<View> mBannerViews = null;
	 private ViewPager mBannerViewPager;
	 private HomeBannersAdapter homeBannerAdapter;
	 /**
	  * 首页滚动图底部标识
	  */
	 private LinearLayout ll_point;
	 private ImageView[] imageViews;
	 private int[] images;
	 
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		myApp = (MyApplication) getActivity().getApplication();
		if(view == null){ 
			view = inflater.inflate(R.layout.fragment_main_login, container, false); 
		}else{
			 
		}
		//缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。  
        ViewGroup parent = (ViewGroup) view.getParent();  
        if (parent != null) {  
            parent.removeView(view);  
        }    
		
		initView();
		getConfig();
		return view;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
//		Log.e("Tt", "~~~MainLoginFragment~~~~~~~onActivityCreated");
	}

	@Override
	public void onResume() { 
		super.onResume();
//		Log.e("Tt", "~~~~~~MainLoginFragment~~~~onResume");
	}
	
	public void initView() {
		mRequestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
		iv_nologin = (ImageButton)view.findViewById(R.id.iv_nologin);
		iv_nologin.setOnClickListener(this);
//		btnLoginkf = (Button) view.findViewById(R.id.btn_login_koufu);
//		btnLoginOther = (Button) view.findViewById(R.id.btn_login_other);
//		btnLoginkf.setOnClickListener(this);
//		btnLoginOther.setOnClickListener(this);
		mBannerViewPager = (ViewPager) view.findViewById(R.id.main_viewpager);
		ll_point = (LinearLayout)view.findViewById(R.id.ll_point);
		pb_wait = (ProgressBar)view.findViewById(R.id.pb_wait);
		ly_mainlogin = (LinearLayout)view.findViewById(R.id.ly_mainlogin);
		initBanners();
		MainActivity mainActivity = (MainActivity) getParentFragment().getActivity();
		mainActivity.sm.addIgnoredView(mBannerViewPager);
		mainActivity.btnRefresh.setEnabled(false);
	}
	/**
	 * 刷新功能
	 */
	public void onRefresh() {   
		 
	}
	private void initBanners(){
		images = new int[]{R.drawable.banner_1,R.drawable.banner,R.drawable.banner_1};
		if(mBannerViews==null)
			mBannerViews = new ArrayList<View>();
		mBannerViews.clear();
		for (int i = 0; i < images.length; i++) {   
			ImageView image = new ImageView(getActivity());
			image.setDrawingCacheEnabled(true);
			image.setBackgroundResource(images[i]); 
			image.setScaleType(ScaleType.CENTER_CROP);
			mBannerViews.add(image);  
		}
		
		if(homeBannerAdapter!=null){
			homeBannerAdapter.setViews(mBannerViews); 
		}else{
			homeBannerAdapter = new HomeBannersAdapter(mBannerViews);
			mBannerViewPager.setAdapter(homeBannerAdapter);
			mBannerViewPager.setOnPageChangeListener(this);
		}
		initPoint();
	}
	
	public void initPoint() {
		ll_point = (LinearLayout) view.findViewById(R.id.ll_point);
		ll_point.removeAllViews();
		if(mBannerViews.size()<=1){ 
			return;
		} 
		imageViews = new ImageView[mBannerViews.size()];
		for (int i = 0; i < mBannerViews.size(); i++) {
			ImageView imageView = new ImageView(getActivity());
			imageView.setBackgroundResource(R.drawable.point_default);
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					new ViewGroup.LayoutParams(60, 18));
			layoutParams.leftMargin = 11;
			layoutParams.rightMargin = 11;
			imageViews[i] = imageView;
			if (i == 0) {
				imageViews[i].setBackgroundResource(R.drawable.point_select);
			} else {
				imageViews[i].setBackgroundResource(R.drawable.point_default);
			}
			ll_point.addView(imageView, layoutParams);
		}
	}
	
	public void updataIndicaterorPoint(int pos){
		pos = pos%mBannerViews.size();
		for(int i=0;i<imageViews.length;i++){
			if(i==pos){
				imageViews[i].setBackgroundResource(R.drawable.point_select);
			}else{
				imageViews[i].setBackgroundResource(R.drawable.point_default);
			}
		}

	}
	@Override
	public void onPause() {
		super.onPause(); 
	}
	@Override
	public void onStop() {  
		super.onStop();
	}
	public void onDestroy() { 
		super.onDestroy();
	}
	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
		case R.id.iv_nologin: 
		    intent = new Intent(getActivity(),LoginActivity.class);
			getParentFragment().startActivityForResult(intent, 3); 
			break;
		default:
			break;
		}

	}

	@Override
	public void onPageScrollStateChanged(int arg0) { 
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) { 
		
	}

	@Override
	public void onPageSelected(int position) { 
		//更新显示指示点
		updataIndicaterorPoint(position);	
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) { 
		super.onActivityResult(requestCode, resultCode, data);
//		Log.e("Tt", "onActivityResult login");
	}
	
	
	/**
	 * 获取手续费率
	 */
	private void getConfig(){
		String url = Statics.URL_PHP + "getConfig";
		stringRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {

			@Override
			public void onResponse(String response) { 
				if(response!=null && !response.equals("")){
					try {
						JSONObject obj = new JSONObject(response);
						int status = obj.getInt("status");
						if(status == 0){
							String _data = obj.getString("data");
							if(_data!=null && !_data.equals("null")){ 
								JSONObject data = new JSONObject(obj.getString("data"));
								String hand_fee_buy = data.getString("hand_fee_buy");
								String hand_fee_sell = data.getString("hand_fee_sell");
								myApp.setHandfreebuy(hand_fee_buy);
								myApp.setHandfreesale(hand_fee_sell); 
							}
						}
						pb_wait.setVisibility(View.GONE);
						ly_mainlogin.setVisibility(View.VISIBLE);
					} catch (JSONException e) { 
						e.printStackTrace();
					}
					
				}
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				error.printStackTrace();
				pb_wait.setVisibility(View.GONE);
				ly_mainlogin.setVisibility(View.VISIBLE);
			}
		});
		mRequestQueue.add(stringRequest);
	}
}
